package com.maoning.product.service.impl;

import com.maoning.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.product.dao.BrandDao;
import com.maoning.product.entity.BrandEntity;
import com.maoning.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        final String key = (String) params.get("key");
        final QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 之所以出现这个方法,是因为关系表中为了避免笛卡尔积,所以把id和name作为冗余存储了.那么一次更新就需要更新多张表保证一致性
     * @param brand
     */
    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        this.updateById(brand);
        //如果品牌对象的名字不为空,那么还需要更新关系表
        if(StringUtils.isNotEmpty(brand.getName())){
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
            // TODO: 2021/10/12 如果还有其他关联表,那么也需要在这里一起更新
        }
    }

    @Cacheable(value = "brand",key = "'brandIds:' + #root.args[0]")
    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
        final List<BrandEntity> list = this.list(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
        return list;
    }

}